package com.lys.controller;

import com.lys.entity.User;
import com.lys.service.UserService;
import com.lys.utils.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.List;

/**
 * @author 陆小根
 * @version 9.0.4
 * @Date 2022/5/29 23:16
 */
@Controller
@RequestMapping("/user")
public class UserController {

    @Autowired
    private UserService userService;

    /**
     * 跳到登录页面
     * @return
     */
    @GetMapping("/toLogin")
    public String toLogin() {
        return "/pre/login";
    }


    /**
     * 登录方法
     * @param session
     * @return
     */
    @PostMapping("/Login")
    @ResponseBody
    public ReturnResult login(@RequestParam("loginName") String loginName,
                              @RequestParam("password") String password,
                              HttpSession session) {
        ReturnResult result=new ReturnResult();
        //参数获取
        User user=userService.getUser(null, loginName);
        if(EmptyUtils.isEmpty(user)){
            result.returnFail("用户不存在");
        }else{
            if(user.getPassword().equals(SecurityUtils.md5Hex(password))){
                //登陆成功
                session.setAttribute("loginUser", user);
                result.returnSuccess("登陆成功");
            }else{
                result.returnFail("密码错误");
            }
        }
        return result;
    }

    /**
     * 退出登录
     * @param session
     * @param response
     * @return
     */
    @RequestMapping("/logout")
    public String loginOut(HttpSession session, HttpServletResponse response) {
        ReturnResult result=new ReturnResult();
        try {
            User user=(User)session.getAttribute("loginUser");
            if (user != null) {
                session.removeAttribute("loginUser");
                // 清除购物车
                session.removeAttribute("cart");
                session.removeAttribute("cart2");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        result.returnSuccess("注销成功");
        return "/pre/login";
    }

    /**
     * 跳到注册页面
     * @return
     */
    @GetMapping("/toRegister")
    public String toRegister()  {
        return "/pre/register";
    }

    /**
     * 保存用户信息  注册。。
     * @param request
     * @return
     */
    @PostMapping("/Register")
    @ResponseBody
    public ReturnResult saveUserToDatabase(HttpServletRequest request,
                                           User user) {
        ReturnResult result = new ReturnResult();
        try {
            User oldUser = userService.getUser(null, user.getLoginName());
            //判断用户
            if (EmptyUtils.isNotEmpty(oldUser)) {
                result.returnFail("用户已经存在");
                return result;
            }
            user.setPassword(SecurityUtils.md5Hex(request.getParameter("password")));
            user.setType(Constants.UserType.PRE);
            result=checkUser(user);
            //是否验证通过
            if(result.getStatus()==Constants.ReturnResult.SUCCESS){
                if(!userService.add(user)){
                    return result.returnFail("注册失败！");
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        result.returnSuccess("注册成功");
        return result;
    }

    private ReturnResult checkUser(User user){
        ReturnResult result = new ReturnResult();
        boolean flag=true;
        if(EmptyUtils.isNotEmpty(user.getMobile())){
            if(!RegUtils.checkMobile(user.getMobile())){
                return result.returnFail("手机格式不正确");
            }
        }

        if(EmptyUtils.isNotEmpty(user.getIdentityCode())){
            if(!RegUtils.checkIdentityCodeReg(user.getIdentityCode())){
                return result.returnFail("身份证号码不正确");
            }
        }

        if(EmptyUtils.isNotEmpty(user.getEmail())){
            if(!RegUtils.checkEmail(user.getEmail())){
                return result.returnFail("邮箱格式不正确");
            }
        }
        return result.returnSuccess();
    }



    /*
        后台用户管理
        AdminUser
     */


    //===============================================================================
    /**
     * 跳到用户主页
     *
     * @param model
     * @return
     */
    @GetMapping("/admin/index")
    public String index(HttpSession session,
                        Model model) {
        //获取登陆用户
        User user = (User) session.getAttribute("loginUser");
        model.addAttribute("user", user);
        model.addAttribute("menu", 2);
        return "/backend/user/userInfo";
    }

    /**
     * 订单的主页面
     * @return
     */
    @GetMapping("/admin/list")
    public String queryUserList(@RequestParam(value = "currentPage",required = false) String currentPageStr,
                                @RequestParam(value = "pageSize",required = false) String pageSize,
                                Model model) {
        //获取当前页数
        // String currentPageStr = request.getParameter("currentPage");
        //获取页大小
        //String pageSize = request.getParameter("pageSize");
        int rowPerPage = EmptyUtils.isEmpty(pageSize) ? 10 : Integer.parseInt(pageSize);
        int currentPage = EmptyUtils.isEmpty(currentPageStr) ? 1 : Integer.parseInt(currentPageStr);
        int total = userService.count();
        Pager pager = new Pager(total, rowPerPage, currentPage);
        List<User> userList = userService.getUserList(currentPage, rowPerPage);
        pager.setUrl("user/admin/list");
        model.addAttribute("userList", userList);
        model.addAttribute("pager", pager);
        model.addAttribute("menu", 8);
        return "/backend/user/userList";
    }

    /**
     * 修改用户信息
     * @return
     * @throws Exception
     */
    @GetMapping("/admin/toUpdate")
    public String toUpdateUser(@RequestParam("id") String id,
                               Model model) {
        // String id = request.getParameter("id");
        User user = userService.getUser(Integer.parseInt(id), null);
        model.addAttribute("user", user);
        return "/backend/user/toUpdateUser";
    }

    /**
     * 去添加用户
     * @return
     * @throws Exception
     */
    @GetMapping("/admin/toAdd")
    public String toAddUser(Model model) {
        User user = new User();
        model.addAttribute("user", user);
        return "/backend/user/toUpdateUser";
    }
    /**
     * 更新用户
     * @param request
     * @return
     * @throws Exception
     */
    @PostMapping("/admin/saveOrUpdate")
    @ResponseBody
    public ReturnResult updateUser(HttpServletRequest request,
                                   User user) {
        ReturnResult result = new ReturnResult();
        Integer id = user.getId();
        //User user = new User();
        String loginName = user.getLoginName();
        //String sex = request.getParameter("sex");
        User oldUser = userService.getUser(null, loginName);

        //判断用户
        if (EmptyUtils.isNotEmpty(oldUser) && (EmptyUtils.isEmpty(id) || oldUser.getId() != id)) {
            result.returnFail("用户已经存在");
            return result;
        }
        //user.setLoginName(loginName);
        //user.setUserName(request.getParameter("userName"));
        user.setSex(EmptyUtils.isEmpty(user.getSex()) ? 1 : 0);
        if (EmptyUtils.isEmpty(id) || id.equals("0")) {
            user.setPassword(SecurityUtils.md5Hex(request.getParameter("password")));
        }
        //user.setIdentityCode(request.getParameter("identityCode"));
        //user.setEmail(request.getParameter("email"));
        //user.setMobile(request.getParameter("mobile"));
        //user.setType(Integer.parseInt(request.getParameter("type")));

        result=checkUser(user);
        //是否验证通过
        if(result.getStatus()==Constants.ReturnResult.SUCCESS){
            if (EmptyUtils.isEmpty(id) || id.equals("0")) {
                if(!userService.add(user)){
                    return result.returnFail("增加失败！");
                }
            } else {
                //user.setId(id);
                if(!userService.update(user)){
                    return result.returnFail("修改失败！");
                }
            }
        }
        result.returnSuccess();
        return result;


    }

    /**
     * 根据id删除用户
     */
    @PostMapping("/admin")
    @ResponseBody
    public ReturnResult deleteUserById(@RequestParam("id") String id) {
        ReturnResult result = new ReturnResult();
        // String id = request.getParameter("id");
        userService.deleteUserById(Integer.parseInt(id));
        result.returnSuccess();
        return result;
    }

}
